/**
 * @author tmh
 * @date 2024/10/16 21:15
 * @description
 */
public class T38外观数列 {
    public String countAndSay(int n) {
        String result = "1";
        for (int i = 1; i < n; i++) {
            result = getNextSequence(result);
        }
        return result;
    }

    private String getNextSequence(String sequence) {
        StringBuilder builder = new StringBuilder();
        int len = sequence.length();
        int count = 1;
        for (int i = 1; i < len; i++) {
            if (sequence.charAt(i - 1) == sequence.charAt(i)) {
                count++;
            } else {
                builder.append(count).append(sequence.charAt(i - 1));
                //重置count=1
                count = 1;
            }
        }
        //处理最后一个字符
        builder.append(count).append(sequence.charAt(len - 1));
        return builder.toString();
    }
}
